package com.ys.controller.api.hr;

import com.ys.entity.hr.ThrOperateRegistration;
import com.ys.entity.sys.YsCol;
import com.ys.service.flow.YspTaskService;
import com.ys.service.hr.ThrOperateRegistrationItemService;
import com.ys.service.hr.ThrOperateRegistrationService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/thrOperateRegistration")
public class ApiInterThrOperateRegistrationController {
	
	public static Long MENU_ID = 10201L;
	private static Long MENU_ID_DETAIL = 10202L;

	private static final Logger logger = LoggerFactory.getLogger(ApiInterThrOperateRegistrationController.class);

	@Autowired
	private CommonApiService<ThrOperateRegistration> commonApiService;
	@Autowired
	private ThrOperateRegistrationService thrOperateRegistrationService;

	@Autowired
	private ThrOperateRegistrationItemService thrOperateRegistrationItemService;

	@Autowired
	private YspTaskService yspTaskService;



	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public ThrOperateRegistration setSeachSql(ThrOperateRegistration cond){

		cond.addField("B.UserId AS userId");
		cond.addField("B.UserName AS userName");
		cond.addField("B.HeadUserId AS headUserId");
		cond.addField("B.UserSex AS userSex");
		cond.addField("B.Telephone AS telephone");
		cond.addField("B.Age AS age");
		cond.addField("B.Education AS education");
		cond.addField("B.Work AS work");
		cond.addField("B.Remark AS remark");
		cond.addField("B.OtherFile AS otherFile");
		cond.addField("B.RoleIdAttribute AS roleIdAttribute");
		cond.addField("B.BirthDay AS birthDay");
		cond.addField("CUO.DeptName AS createDeptName");
		cond.addField("CU.RoleName AS createRoleName");
		cond.addField("CU.UserName AS createUser");
		cond.addField("CASE WHEN A.EffectStock = 0  THEN '制单中' ELSE '已完成' END effectStockName ");//流程状态

		cond.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime");
		cond.addField("B.HeadUserId + '/' + U.UserName AS headUserName");
		cond.addField("O.DeptName AS deptName");
		cond.addField("R.Name AS roleName");
		cond.addField("BA1.HigherLevelPath + ',' + BA1.Name AS workCityName");
		cond.addLeftJoin("THR_OperateRegistrationItem B on B.PBid = A.Bid");
		cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ");
		cond.addLeftJoin("TS_OrganizationInfo O ON O.Orgid = B.DeptId AND 1=1");
		cond.addLeftJoin("TS_UserInfo U ON U.UserId = B.HeadUserId AND 1=1");
		cond.addLeftJoin("YS_Role R ON R.Id = B.RoleId AND 1=1");
		cond.addLeftJoin("TB_BaseInfoArea BA1 ON BA1.Code = B.Adcode AND 1=1");
		cond.addLeftJoin("TS_UserChange C on C.Id = A.CreateChangeId");
		cond.addLeftJoin("TS_UserInfo CU on CU.UserId = C.UserId");
		cond.addLeftJoin("TS_OrganizationInfo CUO ON CUO.Id = CU.OrgId");
		cond.addLeftJoin("TB_BaseInfo AA ON AA.Id = B.OfficeId ");

		//排序
		cond.setOrderby("A.Bid DESC");
		cond = commonApiService.dataAuth(MENU_ID, cond);
		return  cond;
	}


	@RequiresPermissions("thrOperateRegistration:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
								 @ModelAttribute ThrOperateRegistration cond
	){
		cond = setSeachSql(cond);
		return commonApiService.searchLay(cond);
	}


	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute ThrOperateRegistration cond, String conditions){
		try {
			cond.setPage(0).setSize(999999);
			cond = setSeachSql(cond);
			//获取菜单字段数据
			List<YsCol> listField = new YsCol()
					.setMenuId(MENU_ID)
					.where("A.Code != 'ope'")
					.setFrontShow(1)
					.setOrderby("A.SortNo asc")
					.queryList();
			//获取数据
			List<Map<String, Object>> listData = cond.queryMap();
			//处理数据
			ExportExcelUtils<ThrOperateRegistration> util = new ExportExcelUtils<>(new ThrOperateRegistration());
			String toFilePath = util.exportExcel(listData, listField, "员工档案");
			UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
			return R.ok(dto.getUrl());
		}catch (Exception e){
			logger.error("导出出错：",e.getMessage(),e);
			return R.error("导出失败，请稍后重试！");
		}
	}

	/**
	 * 新增
	 */
	@RequestMapping("/toAdd")
	@ResponseBody
	public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params, String subData) {
		try {
			logger.info("申请新增传参：" + params);
			return thrOperateRegistrationService.add(params,MENU_ID_DETAIL);
		} catch (Exception e) {
			logger.error("新增出错：", e.getMessage(), e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequestMapping("/toEdit")
	@ResponseBody
	public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			//新增
			return thrOperateRegistrationService.update(params,MENU_ID_DETAIL);
		} catch (Exception e) {
			logger.error("修改出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



	/**
	 * 流转通过
	 */
	@PostMapping("/flowPass")
	@ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		try {
			return thrOperateRegistrationService.flowPass(id, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("流转出错：",e.getMessage(),e);
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/**
	 * 流转驳回
	 */
	@PostMapping("/flowRefuse")
	@ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){

		ThrOperateRegistration entity = new ThrOperateRegistration().setId(id).queryFirst();
		String bid = entity.getBid();
		try {
			return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("驳回出错：",e.getMessage(),e);
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/**
	 * 流转驳回
	 */
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){

		ThrOperateRegistration entity = new ThrOperateRegistration().setId(id).queryFirst();
		String bid = entity.getBid();
		try {
			return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("驳回出错：",e.getMessage(),e);
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public R del(HttpServletRequest request, Long id){
		try {
			return thrOperateRegistrationService.delete(id);
		} catch (Exception e) {
			logger.error("删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


	/**
	 * 删除列表信息
	 */
	@RequestMapping("/toDelItem")
	@ResponseBody
	public R toDelItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
		try {
			for(int i=0;i<idList.size();i++) {
				//删除
				thrOperateRegistrationItemService.del(Long.parseLong(idList.get(i)));
			}
			return R.ok();
		}catch (Exception e) {
			logger.error("删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}

	}


}
